package com.example.accessibilityhelper.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.example.accessibilityhelper.Dispatcher
import com.example.accessibilityhelper.R
import com.example.accessibilityhelper.WeChatHelperService
import com.example.accessibilityhelper.fetchcoporation.FetchAccountCorporationInfoTask
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        init()
    }

    private fun init() {
        val permitted = AndPermission.hasPermissions(this, Permission.WRITE_EXTERNAL_STORAGE)
        if (permitted) {
            doSendMsgTask()
        } else {
            requestPermission()
        }
    }

    private fun doSendMsgTask() {
        Toast.makeText(
            applicationContext,
            R.string.main_prepare_do_task_msg, Toast.LENGTH_SHORT
        )
            .show()
    }

    fun requestPermission() {
        AndPermission.with(this)
            .runtime()
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            .onGranted {
                jumpAccessibilitySettingIfNotGranted()
            }
            .onDenied {
                showPermissionDeniedDialog()
            }
            .start()
    }

    private fun showPermissionDeniedDialog() {
        val dialog = AlertDialog.Builder(this)
            .setMessage(R.string.main_permission_denied_dialog_msg)
            .create()
        dialog.show()
    }

    private fun jumpAccessibilitySettingIfNotGranted() {
        if (hasAccessibilityServiceEnabled().not()) {
            jumpAccessibilitySetting()
        } else {
            doSendMsgTask()
        }
    }

    private fun jumpAccessibilitySetting() {
        val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(intent)
    }

    private fun hasAccessibilityServiceEnabled(): Boolean {

        val enabled = Settings.Secure.getInt(contentResolver, Settings.Secure.ACCESSIBILITY_ENABLED)
        val targetServiceName = WeChatHelperService::class.simpleName
        if (enabled == 1) {
            val textSplitter = TextUtils.SimpleStringSplitter(':')
            val settingValue = Settings.Secure.getString(
                contentResolver,
                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
            )
            textSplitter.setString(settingValue)
            while (textSplitter.hasNext()) {
                val serviceName = textSplitter.next()
                if (serviceName.equals(targetServiceName)) {
                    return true
                }
            }

        }
        return false
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
    }

    fun openAccessibilityService(view: View) {
        jumpAccessibilitySettingIfNotGranted()
    }

    fun openFloatWindow(view: View) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && Settings.canDrawOverlays(this)) {
            launchWindowService()
        } else {
            val intent =
                Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$packageName"))
            startActivityForResult(intent, 101)
        }
    }

    private fun launchWindowService() {
        val intent = Intent()
        intent.action = "com.wechathelper.windowservice"
        intent.`package` = packageName
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            createFloatWindow(this)
            startForegroundService(intent)
        } else {
            startService(intent)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 101 && resultCode == Activity.RESULT_OK) {
            launchWindowService()
        }
    }

    fun detectCorporations(view: View) {
        Dispatcher.finishAndPromote(FetchAccountCorporationInfoTask())
    }
}